/**
 * 
 */
package com.shark.app.common.utils;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import net.sf.cglib.beans.BeanCopier;
import net.sf.cglib.core.Converter;

/**
 * @author lenovo
 * @description
 * @date 2016年8月16日
 */
public class BeanUtils {
	
	private static final Map<String, BeanCopier> BEAN_COPIERS =
			new ConcurrentHashMap<String, BeanCopier>();
	
	private static final Converter convert = new ConverterImpl();
	
	public static void copy(Object srcObj, Object destObj) { 
		String key = genKey(srcObj.getClass(), destObj.getClass());  
        BeanCopier copier = null;  
        if (!BEAN_COPIERS.containsKey(key)) {  
            copier = BeanCopier.create(srcObj.getClass(), destObj.getClass(), false);  
            BEAN_COPIERS.put(key, copier);  
        } else {  
            copier = BEAN_COPIERS.get(key);  
        }  
        copier.copy(srcObj, destObj, convert);  
	}
	
	private static String genKey(Class<?> srcClazz, Class<?> destClazz) {  
        return srcClazz.getName() + destClazz.getName();  
    }
	
	private static class ConverterImpl implements Converter {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		@SuppressWarnings("rawtypes")
		@Override
		public Object convert(Object value, Class target, Object context) {
			if (value instanceof Integer) {  
	            return (Integer) value;  
	        } else if (value instanceof Timestamp) {  
	            Timestamp date = (Timestamp) value;  
	            return sdf.format(date);  
	        } else if (value instanceof BigDecimal) {  
	            BigDecimal bd = (BigDecimal) value;  
	            return bd.toPlainString();  
	        }  
	        return null; 
		}
		
	}
	
}
